import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Msg.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/utils/log_util.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fsuper/fsuper.dart';

class MsgPage extends StatefulWidget {
  @override
  _MsgPageState createState() => _MsgPageState();
}

class _MsgPageState extends State<MsgPage> {
  EasyRefreshController controller = EasyRefreshController();

  int childCount = 0;
  var _item = [];

  @override
  void initState() {
    super.initState();
    _getMsgList();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      enableControlFinishRefresh: true,
      header: CommWidget.commHeader(),
      emptyWidget: childCount == 0 ? CommWidget.nullWidget() : null,
      controller: controller,
      slivers: <Widget>[
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          return _itemWidget(context, index);
        }, childCount: childCount))
      ],
      onRefresh: () => _getMsgList(),
    );
  }

  Widget _itemWidget(BuildContext context, int index) {
    Msg msg = _item[index];
    return Column(
      children: <Widget>[
        SizedBox(height: 10),
        _userWidget(msg),
        _msgWidget(msg),
        Offstage(offstage: msg.msgType == '04', child: _tagWidget(msg)),
        _bottomWidget(msg),
        _dividerWidget(index),
      ],
    );
  }

  ///消息发送者
  Widget _userWidget(Msg msg) {
    String sendName = null == msg.sendName ? "匿名用户" : msg.sendName;
    String imgLogo = Comm.IMG_DEFAULT;
    if (msg.msgType == '04') {
      sendName = "单片机助手";
    }
    Widget headImg = msg.msgType == '04'
        ? Image.asset(
            Comm.IMG_APP_LOGO,
            fit: BoxFit.cover,
            width: 30,
            height: 30,
          )
        : CachedNetworkImage(
            width: 30,
            height: 30,
            imageUrl: Api.getUrl(msg.sendImg),
            fit: BoxFit.cover,
            errorWidget: (context, url, error) => Image.asset(
              Comm.IMG_DEFAULT,
              fit: BoxFit.cover,
            ),
          );
    return FSuper(
      height: 36,
      width: double.infinity,
      child2: ClipRRect(
        borderRadius: BorderRadius.circular(15),
        child: headImg,
      ),
      child2Alignment: Alignment.centerLeft,
      child2Margin: EdgeInsets.only(left: 10),
      spans: [
        TextSpan(
          text: sendName,
          style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
        ),
        TextSpan(
          text: '\n${CommUtil.getTimeDiff(msg.createAt)}',
          style: TextStyle(fontSize: 11, color: Colors.grey),
        ),
      ],
      textAlignment: Alignment.centerLeft,
      textAlign: TextAlign.start,
      padding: EdgeInsets.only(left: 46),
      onChild2Click: () {
        if (msg.msgType != '04') {
          Routers.router.navigateTo(
            context,
            "${Routers.PAGE_USERINFO}?userId=${msg.sendId}",
            transition: TransitionType.inFromRight,
          );
        }
      },
    );
  }

  ///消息内容
  Widget _msgWidget(Msg msg) {
    return Container(
      margin: EdgeInsets.only(top: 4, bottom: 4, left: 10, right: 10),
      alignment: Alignment.centerLeft,
      child: Text(
        msg.content,
        style: TextStyle(fontSize: 16),
      ),
    );
  }

  ///消息针对的预览
  Widget _tagWidget(Msg msg) {
    bool showPic = false;
    String image = "";
    if (null != msg.tagPic) {
      showPic = true;
      image = msg.tagPic.split(",")[0];
    }
    return GestureDetector(
      child: Container(
        height: 66,
        margin: EdgeInsets.only(left: 10, right: 10, top: 4),
        decoration: BoxDecoration(
            color: Color(0xffF2F2F2), borderRadius: BorderRadius.circular(2)),
        child: Row(children: <Widget>[
          Offstage(
              offstage: !showPic,
              child: Container(
                height: 66,
                width: 50,
                child: CachedNetworkImage(
                  imageUrl: Api.getUrl(image),
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      CommWidget.imgError(textSize: 10),
                ),
              )),
          Expanded(
            child: Container(
              height: 70,
              padding: EdgeInsets.only(left: 10),
              alignment: Alignment.centerLeft,
              child: Text(
                null == msg.tagContent ? "用户已删除" : msg.tagContent,
                overflow: TextOverflow.ellipsis,
                maxLines: 3,
                style: TextStyle(color: Colors.grey),
              ),
            ),
            flex: 1,
          )
        ]),
      ),
      onTap: () {
        String url;
        LogUtil.v("点击：${msg.toJson()}");
        if (null == msg.tagId) {
          Toast.show("用户已删除");
          return;
        }
        if ('01' == msg.msgType) {
          url = "${Routers.PAGE_FORUMINFO}?topicId=${msg.tagId}";
          Routers.router
              .navigateTo(context, url, transition: TransitionType.inFromRight);
        } else if ('02' == msg.msgType) {
          url = "${Routers.PAGE_GOOD_INFO}?goodsId=${msg.tagId}";
          Routers.router
              .navigateTo(context, url, transition: TransitionType.inFromRight);
        } else if ('03' == msg.msgType) {
          url = "${Routers.PAGE_ORDERINFO}?orderId=${msg.tagId}";
          Routers.router
              .navigateTo(context, url, transition: TransitionType.inFromRight);
        }
      },
    );
  }

  ///底部按钮
  Widget _bottomWidget(Msg msg) {
    String desc;
    if (msg.msgType == '01') {
      desc = '话题回复';
    } else if (msg.msgType == '02') {
      desc = '商品回复';
    } else if (msg.msgType == '03') {
      desc = '订单消息';
    } else if (msg.msgType == '04') {
      desc = '系统通知';
    }
    return FSuper(
      text: desc,
      textSize: 12,
      textAlignment: Alignment.centerLeft,
      textColor: Color(0xffbbbbbb),
      margin: EdgeInsets.only(left: 10, top: 10, bottom: 8),
      padding: EdgeInsets.only(left: 4, right: 4, top: 2, bottom: 2),
    );
  }

  ///分隔线
  Widget _dividerWidget(int index) {
    if (index == childCount - 1) {
      return Container(height: 1);
    } else {
      return Container(height: 8, color: Color(0xffF2F2F2));
    }
  }

  ///获取消息列表
  Future _getMsgList() async {
    await Http.get("${Api.URL_MSG_LIST}", successCallBack: (data) {
      List list = json.decode(data).map((m) => Msg.fromJson(m)).toList();
      controller.finishRefresh();
      setState(() {
        if (null != list) {
          _item.clear();
          childCount = list.length;
          _item.addAll(list);
        }
      });
    }, errorCallBack: (msg) {
      controller.finishRefresh();
    });
  }
}
